using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OneAuthCenter.Application.DTOs.Client;
using OneAuthCenter.Application.Services;

namespace OneAuthCenter.API.Controllers;

/// <summary>
/// 客户端管理控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize(Roles = "Admin")]
public class ClientController : ControllerBase
{
    private readonly IClientService _clientService;
    private readonly ILogger<ClientController> _logger;

    public ClientController(IClientService clientService, ILogger<ClientController> logger)
    {
        _clientService = clientService;
        _logger = logger;
    }

    /// <summary>
    /// 获取所有客户端
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(IEnumerable<ClientDto>), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetAll()
    {
        try
        {
            var clients = await _clientService.GetAllClientsAsync();
            return Ok(clients);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取客户端列表时发生错误");
            return StatusCode(500, new { message = "获取客户端列表失败" });
        }
    }

    /// <summary>
    /// 根据客户端 ID 获取客户端
    /// </summary>
    [HttpGet("{clientId}")]
    [ProducesResponseType(typeof(ClientDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Get(string clientId)
    {
        try
        {
            var client = await _clientService.GetClientAsync(clientId);
            if (client == null)
            {
                return NotFound(new { message = $"客户端 '{clientId}' 不存在" });
            }
            return Ok(client);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取客户端时发生错误");
            return StatusCode(500, new { message = "获取客户端失败" });
        }
    }

    /// <summary>
    /// 创建新客户端
    /// </summary>
    [HttpPost]
    [ProducesResponseType(typeof(ClientDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> Create([FromBody] CreateClientRequest request)
    {
        try
        {
            var client = await _clientService.CreateClientAsync(request);
            return CreatedAtAction(nameof(Get), new { clientId = client.ClientId }, client);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning(ex, "创建客户端失败: {ClientId}", request.ClientId);
            return BadRequest(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建客户端时发生错误");
            return StatusCode(500, new { message = "创建客户端失败" });
        }
    }

    /// <summary>
    /// 更新客户端
    /// </summary>
    [HttpPut("{clientId}")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Update(string clientId, [FromBody] CreateClientRequest request)
    {
        try
        {
            await _clientService.UpdateClientAsync(clientId, request);
            return NoContent();
        }
        catch (KeyNotFoundException ex)
        {
            _logger.LogWarning(ex, "更新客户端失败: {ClientId}", clientId);
            return NotFound(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新客户端时发生错误");
            return StatusCode(500, new { message = "更新客户端失败" });
        }
    }

    /// <summary>
    /// 删除客户端
    /// </summary>
    [HttpDelete("{clientId}")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Delete(string clientId)
    {
        try
        {
            await _clientService.DeleteClientAsync(clientId);
            return NoContent();
        }
        catch (KeyNotFoundException ex)
        {
            _logger.LogWarning(ex, "删除客户端失败: {ClientId}", clientId);
            return NotFound(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除客户端时发生错误");
            return StatusCode(500, new { message = "删除客户端失败" });
        }
    }

    /// <summary>
    /// 重置客户端密钥
    /// </summary>
    [HttpPost("{clientId}/reset-secret")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> ResetSecret(string clientId)
    {
        try
        {
            var newSecret = await _clientService.ResetClientSecretAsync(clientId);
            return Ok(new { clientId, clientSecret = newSecret });
        }
        catch (KeyNotFoundException ex)
        {
            _logger.LogWarning(ex, "重置客户端密钥失败: {ClientId}", clientId);
            return NotFound(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "重置客户端密钥时发生错误");
            return StatusCode(500, new { message = "重置客户端密钥失败" });
        }
    }
}

